package com.boot.springboot.exception;
import com.boot.springboot.pojo.ResponseMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


@RestControllerAdvice
public class GlobalExceptionHandler {

    Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    // 处理参数校验失败（如@NotNull、@Min等）
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseMessage handleValidException(MethodArgumentNotValidException e) {
        String msg = e.getBindingResult().getFieldError().getDefaultMessage(); // 获取校验失败信息
        return new ResponseMessage(400, msg, null); // 400：客户端参数错误
    }
    // 处理JSON解析错误（如前导零）
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ResponseMessage handleJsonError(HttpMessageNotReadableException e) {
        return new ResponseMessage(400, "请求参数格式错误：" + e.getMessage(), null);
    }

    // 处理业务异常（如查询不存在的ID）
    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseMessage handleBizException(IllegalArgumentException e) {
        return new ResponseMessage(404, e.getMessage(), null); // 404：资源不存在
    }

    // 其他未知异常
    @ExceptionHandler(Exception.class)
    public ResponseMessage handleOtherException(Exception e) {
        log.error("系统异常", e);
        return new ResponseMessage(500, "服务器内部错误", null); // 500：服务器错误
    }

}
